<script lang="ts">
export default {
    name: "Pagination",
    props:{
        pageNo:{
            type:Number,
            default:1
        },
        total:{
            type:Number,
            default:1
        },
        pageSize:{
            type:Number,
            default:1
        },
        continue:{
            type:Number,
            default:5
        }
    },
    methods:{
        changePage(e){
            if(e.target.nodeName === "BUTTON"){
                if(e.target.dataset.page/1=== this.pageNo) return;
                this.$emit("change-page",{pageNo:e.target.dataset.page/1});
            }
        }
    },
    computed:{
        pageSum(){
            return Math.ceil(this.total/this.pageSize);
        },
        position(){
            let start = this.pageNo-(this.continue-1)/2;
            if(start<1) start = 1;
            let end = start+this.continue-1;
            if(end > this.pageSum){
                end = this.pageSum;
                start = this.pageSum-this.continue+1;
                if(start<1) start = 1;
            }
            return {
                start,
                end
            }
        }
    }
}
</script>

<template>
    <div @click="changePage" class="pagination">
        <button :data-page="pageNo-1" v-if="pageNo>1">上一页</button>
        <button :data-page="1" v-if="position.start>1">1</button>
        <span v-if="position.start>2">···</span>

        <button :data-page="position.start+page-1" :class="{active:pageNo===(position.start+page-1)}" v-for="page in (position.end-position.start+1)" :key="page">{{position.start+page-1}}</button>

        <span  v-if="position.end<pageSum-1">···</span>
        <button :data-page="pageSum"  v-if="position.end<pageSum">{{pageSum}}</button>
        <button :data-page="pageNo+1"  v-if="pageNo<pageSum">下一页</button>

        <span>共 {{total}} 条</span>
    </div>
</template>

<style scoped lang="less">
.pagination {
    text-align: center;
    margin-bottom: 10px;
    button {
        margin: 0 5px;
        background-color: #f4f4f5;
        color: gray;
        outline: none;
        border-radius: 2px;
        padding: 0 4px;
        vertical-align: top;
        display: inline-block;
        font-size: 13px;
        min-width: 35.5px;
        height: 28px;
        line-height: 28px;
        cursor: pointer;
        box-sizing: border-box;
        text-align: center;
        border: 0;

        &[disabled] {
            color: #c0c4cc;
            cursor: not-allowed;
        }

        &.active {
            cursor: not-allowed;
            background-color: #c81623;
            color: #fff;
        }
    }

    span {
        display: inline-block;
        line-height: 28px;
        font-size: 14px;
        color: gray;
        vertical-align: middle;
    }
}
</style>
